package com.hll.spring_book.service.book;

import com.hll.spring_book.mapper.book.BookMapper;
import com.hll.spring_book.pojo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author: Mr.Hu
 * @create: 2021-03-17 22:25
 */
@Service("bookService")
public class BookServiceImpl implements BookService {
  @Autowired private BookMapper bookMapper;

  /**
   * 查询多条数据
   *
   * @param book 实例对象
   * @return 对象列表
   */
  @Override
  public List<Book> queryAll(Book book) {
    return bookMapper.queryAll(book);
  }

  /**
   * 通过ID查询单条数据
   *
   * @param id 主键
   * @return 实例对象
   */
  @Override
  public Book queryById(Integer id) {
    return this.bookMapper.queryById(id);
  }

  /**
   * 新增数据
   *
   * @param book 实例对象
   * @return 实例对象
   */
  @Transactional(
      propagation = Propagation.REQUIRED,
      isolation = Isolation.DEFAULT,
      timeout = 36000,
      rollbackFor = Exception.class)
  @Override
  public Book insert(Book book) {
    this.bookMapper.insert(book);
    return queryById(book.getId());
  }

  /**
   * 修改数据
   *
   * @param book 实例对象
   * @return 实例对象
   */
  @Transactional(
      propagation = Propagation.REQUIRED,
      isolation = Isolation.DEFAULT,
      timeout = 36000,
      rollbackFor = Exception.class)
  @Override
  public Book update(Book book) {
    this.bookMapper.update(book);
    return this.queryById(book.getId());
  }

  /**
   * 通过主键删除数据
   *
   * @param id 主键
   * @return 是否成功
   */
  @Transactional(
      propagation = Propagation.REQUIRED,
      isolation = Isolation.DEFAULT,
      timeout = 36000,
      rollbackFor = Exception.class)
  @Override
  public boolean deleteById(Integer id) {
    return this.bookMapper.deleteById(id) > 0;
  }

  @Override
  public boolean isBookExist(String name, String author) {
    return bookMapper.checkBookExist(name, author) > 0;
  }
}
